<template>
  <div class="myVideo-video" v-if="typeof monitorList!='undefined'&&monitorList.length>0">
    <video
      v-for="(item,index) in monitorList"
      :id="'videoElement' + item.supervisoryId"
      :key="index"
      style="width: 200px;height: 100px"
      muted
      autoplay
    />
  </div>

</template>
<script>
  import flvjs from 'flv.js'

  export default {
    props: {
      appName: String,
      monitorList: Array
    },
    name: 'vedio',
    data() {
      return {      // 视频播放
        url: "http://localhost/rtmpLive?app=live&stream=5",
        rtsplist: [
          {
            src: "http://localhost/rtmpLive?app=live&stream=5",
            id: null
          }
        ],
      }
    },
    // 调用和销毁
    mounted() {
      this.$nextTick(() => {
        this.rtsplist = this.monitorList
        this.createVideo()
      })
    },
    beforeDestroy() {
      this.destoryVideo()
    },
    // watch: {
    //   rtsplist(val) {
    //     val.forEach(item=>{
    //       var videoElement = document.getElementById('videoElement' + item.supervisoryId)
    //       if(videoElement==null||typeof videoElement=='undefined'){
    //         this.createDomPlayer(item)
    //       }
    //     })
    //   }
    // },

    methods: {
      // 创建和销毁video
      createVideo() {
        if (this.rtsplist.length > 0) {
          // let item = this.rtsplist[0]
          // this.createDomPlayer(item)
          this.rtsplist.forEach(item=>{
            console.log(item)
            this.createDomPlayer(item)
          })
        }
      },
      createDomPlayer(data) {
        if (flvjs.isSupported()) {
          var videoElement = document.getElementById('videoElement' + data.supervisoryId)
          this.flvPlayer = flvjs.createPlayer(
            {
              type: 'flv',
              isLive: true,
              hasAudio: false,
              url: data.src
            }, {
              enableStashBuffer: false,
              fixAudioTimestampGap: false,
              isLive: true
            }
          )
          this.flvPlayer.attachMediaElement(videoElement)
          this.flvPlayer.load()
          this.flvPlayer.play()
          // 报错重连
          this.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
            // console.log('errorType:', errType)
            // console.log('errorDetail:', errDetail)
            if (this.flvPlayer) {
              this.destoryVideo()
              setTimeout(function () {
                console.log("等待连接")
              }, 10000)
              this.createVideo()
            }
          })
        }
      },

      destoryVideo() {
        this.flvPlayer.pause()
        this.flvPlayer.unload()
        this.flvPlayer.detachMediaElement()
        this.flvPlayer.destroy()
        this.flvPlayer = null
      }
    }
  }
</script>
